/**
   Copyright 2011 Attila Fekete

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
 */

package org.afekete.filemetadatacreator;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.util.List;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.namespace.QName;

import org.afekete.filemetadatacreator.generated.Metadatacollection;
import org.afekete.filemetadatacreator.generated.ObjectFactory;

/**
 * Class implements export to XML file using the JAXB technology.
 * 
 * @author afekete
 *
 */

public class XMLExporter {
	
	/**
	 * Generates XML file with meta data of files.
	 * @param versionPath 
	 * 
	 * @param metaDataList list of meta data of files
	 * @param exportFile output filename
	 * @throws JAXBException if something went wrong during the XML generation
	 * @throws IOException if something went wrong in file handling
	 */
	public static void export(String versionPath, List<Metadatacollection.Metadata> metaDataList, File exportFile) throws JAXBException, IOException {
		
		final FileOutputStream fis = new FileOutputStream(exportFile);
        final PrintStream printer = new PrintStream(fis);
		printer.print("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>");
		
		ObjectFactory factory = new ObjectFactory();
        Metadatacollection metaDataCollection = factory.createMetadatacollection();
        metaDataCollection.setVersionpath(versionPath);
		for (Metadatacollection.Metadata metaData : metaDataList)
			metaDataCollection.getMetadata().add(metaData);
		JAXBElement<Metadatacollection> metaDataCollectionElement = new JAXBElement<Metadatacollection>(new QName("metadatacollection"), Metadatacollection.class, metaDataCollection);
		
		JAXBContext jc = JAXBContext.newInstance("org.afekete.filemetadatacreator.generated");
        Marshaller m = jc.createMarshaller();
        m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
        m.setProperty(Marshaller.JAXB_FRAGMENT, true);
		m.marshal(metaDataCollectionElement, fis);
		fis.close();
		
	}

}
